"use client";
import { CaretDownOutlined, CaretRightOutlined } from "@ant-design/icons";
import {
  List,
  EditButton,
  ShowButton,
  DeleteButton,
  useTable,
} from "@refinedev/antd";
import { Space, Table, Tag } from "antd";
import { useEffect, useState } from "react";

function buildTree(list: any[]) {
  const map: Record<number, any> = {};
  const roots: any[] = [];
  list.forEach(item => {
    map[item.id] = { ...item, children: [] };
  });
  list.forEach(item => {
    if (item.fid && map[item.fid]) {
      map[item.fid].children.push(map[item.id]);
    } else {
      roots.push(map[item.id]);
    }
  });
  return roots;
}

export default function CategoryList() {
  const [datas, setDatas] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const { tableProps, setCurrent, setPageSize, tableQueryResult } = useTable({
    resource: "project/category/list",
    syncWithLocation: true,
    hasPagination: false,
  });

  useEffect(() => {
    const res = tableProps?.dataSource as any;
    if (res && res.data) {
      const { list, total } = res.data;
      setDatas(buildTree(list));
      setTotal(total);
    }
  }, [tableProps?.dataSource]);

  return (
    <List>
      <Table
        dataSource={datas}
        rowKey="id"
        loading={tableProps?.loading}
        pagination={false}
        expandable={{
          defaultExpandAllRows: true,
          rowExpandable: record => Array.isArray(record.children) && record.children.length > 0,
          expandIcon: ({ expanded, onExpand, record }) =>
            Array.isArray(record.children) && record.children.length > 0 ? (
              <span style={{ cursor: "pointer", marginRight: 4 }} onClick={e => onExpand(record, e)}>
                {expanded ? <CaretDownOutlined style={{ color: '#1890ff' }} /> : <CaretRightOutlined style={{ color: '#1890ff' }} />}
              </span>
            ) : (
              <span style={{ marginRight: 4, width: 16, display: 'inline-block' }}></span>
            ),
          indentSize: 16,
        }}
      >
        <Table.Column dataIndex="id" title={"ID"} />
        <Table.Column dataIndex="alias" title={"别名"} />
        <Table.Column dataIndex="fid" title={"父ID"} />
        <Table.Column dataIndex="sort" title={"排序"} />
        <Table.Column dataIndex="status" title={"状态"} render={(value) => (
          value === 1 ? <Tag color="green">启用</Tag> : <Tag color="red">禁用</Tag>
        )} />
        <Table.Column
          title={"操作"}
          dataIndex="actions"
          render={(_, record) => (
            <Space>
              <EditButton hideText size="small" recordItemId={record.id} />
              <ShowButton hideText size="small" recordItemId={record.id} />
              <DeleteButton hideText size="small" recordItemId={record.id} onSuccess={() => {
                tableQueryResult.refetch();
              }} />
            </Space>
          )}
        />
      </Table>
    </List>
  );
} 